﻿using Microsoft.Xna.Framework;
using System;

namespace Serious
{
    public struct Rectangle2i
    {
        public Index2 Origin;
        public Index2 Size;

        public Index2 LowLow
        {
            get { return  Origin; }
            set { Origin = value; }
        }
        public Index2 LowHi
        {
            get { return new Index2(Origin.X, Origin.Y + Size.Y); }
            set { Origin.X = value.X; Origin.Y = value.Y - Size.Y; }
        }

        public Index2 HiLow
        {
            get { return new Index2(Origin.X + Size.X, Origin.Y + Size.Y); }
            set { Origin.X = value.X; Origin.Y = value.Y - Size.Y; }
        }
        public Index2 HiHi
        {
            get { return Origin + Size; }
            set { Origin = value - Size; }
        }

        public Rectangle2i(Index2 origin, Index2 size)
        {
            Origin = origin;
            Size = size;
        }
        public Rectangle2i(int originX, int originY, int sizeWidth, int sizeHeight) :
            this(new Index2(originX, originY), new Index2(sizeWidth, sizeHeight))
        {
        }

        public static Rectangle2i FromPoints(Index2 p1, Index2 p2)
        {
            Index2 pMin = Index2.Min(p1, p2);
            Index2 pMax = Index2.Max(p1, p2);
            return new Rectangle2i(pMin, pMax - pMin);
        }

        public static Rectangle2i ConvertFromXnaRectangle(Rectangle r)
        {
            return new Rectangle2i(r.X, r.Y, r.Width, r.Height);
        }

        public static explicit operator Rectangle2(Rectangle2i r)
        {
            return new Rectangle2((Vector2)r.Origin, (Vector2)r.Size);
        }

        public int Left
        {
            get { return Origin.X; }
            set { Origin.X = value; }
        }
        public int Right
        {
            get { return Origin.X + Size.X; }
            set { Origin.X = value - Size.X; }
        }

        public int Top
        {
            get { return Origin.Y; }
            set { Origin.Y = value; }
        }
        public int Bottom
        {
            get { return Origin.Y + Size.Y; }
            set { Origin.X = value - Size.Y; }
        }

        public void Translate(Index2 offset)
        {
            Origin += offset;
        }
        
        public static Rectangle2i operator +(Rectangle2i rect, Index2 offset)
        {
            rect.Translate(offset);
            return rect;
        }
        public static Rectangle2i operator -(Rectangle2i rect, Index2 offset)
        {
            rect.Translate(-offset);
            return rect;
        }
    }
}
